package com.hqbzl.chat.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.hqbzl.chat.factory.Factory;
import com.hqbzl.chat.model.Group;
import com.hqbzl.chat.service.GroupSession;
import io.netty.channel.Channel;

public class GroupSessionImpl implements GroupSession {

    final ConcurrentHashMap<String, Group> groupMap = new ConcurrentHashMap<>();

    @Override
    public Group createGroup(String groupName, Set<String> members) {
        final Group build = Group.builder().groupName(groupName).members(members).build();
        groupMap.put(build.getGroupName(), build);
        return build;
    }

    @Override
    public Group joinGroup(String groupName, String member) {
        final Group group = groupMap.get(groupName);
        group.getMembers().add(member);
        return group;
    }

    @Override
    public Group removeMember(String groupName, String member) {
        final Group group = groupMap.get(groupName);
        final Set<String> members = group.getMembers();
        final Iterator<String> iterator = members.iterator();
        while (iterator.hasNext()) {
            final String next = iterator.next();
            if (member.equals(next)) {
                iterator.remove();
            }
        }
        return groupMap.get(groupName);
    }

    @Override
    public Group removeGroup(String groupName) {
        return groupMap.remove(groupName);
    }

    @Override
    public Set<String> getMembers(String groupName) {
        final Group group = groupMap.get(groupName);
        final Set<String> members = group.getMembers();
        return members;
    }

    @Override
    public List<Channel> getMemberChannel(String groupName) {
        final Set<String> members = groupMap.get(groupName).getMembers();
        return members.stream().map(x -> Factory.session.getChannel(x)).filter(Objects::nonNull).collect(Collectors.toList());
    }

    @Override
    public Group query(String groupName) {
        return groupMap.get(groupName);
    }
}
